<?php

namespace Yearnfar\Bundle\CmsBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Yearnfar\Component\Image\Image;

/**
 * @Route("/image")
 * @Template()
 */
class ImageController extends BaseController
{
    /**
     * @Route("/")
     */
    public function indexAction()
    {
        $request = $this->get('request');
        $id = $request->get('id');
        $submit = $request->get('submit');

        if ($id > 0) {
            $em = $this->getDoctrine()->getManager();
            $current = $em->find("CmsBundle:image", $id);

            if ($submit) {
                $tid  = $request->get('tid', 0);
                $name = $request->get('name', '');
                $description = $request->get('description', '');

                if ($tid!=$current->getTid()) {
                    $term = $em->find('CmsBundle:term', $tid);
                    if (!$term) {
                        return $this->msgOut("分类不存在！", '/cms/image/');
                    }
                } else {
                    $term = $current->getTerm();
                }

                $current
                    ->setTerm($term)
                    ->setName($name)
                    ->setDescription($description)
                    ->setLogtime(time());

                $em->flush();

                return $this->msgOut("修改成功！", '/cms/image/');
            } else {

                $ots = $em
                    ->createQuery("SELECT t FROM CmsBundle:term t WHERE t.identify=?1 OR SUBSTRING(t.identify, 1, 6)=?2")
                    ->setParameter(1, 'image')
                    ->setParameter(2, 'image_')
                    ->getResult();

                $term = [];
                $this->enumTerm($term, $ots, 0, -1);

                $parameters = ['oper'=>'modify', 'current'=>$current, 'term'=>$term];
                return $this->render("CmsBundle:image:edit.html.twig", $parameters);
            }

        } else {
            $em = $this->getDoctrine()->getManager();
            $cq = $em
                ->createQuery("SELECT i FROM CmsBundle:image i WHERE i.deltime=?1 ORDER BY i.logtime DESC")
                ->setParameter(1, 0)
                ->setMaxResults(50);

            $images = $cq->getResult();
            $img = [];
            foreach ($images as $image) {
                $day = date('Y年m月d日', $image->getLogtime());

                $img[$day][] = $image;
            }
        }

        return ['img' => $img];
    }

    /**
     * @Route("/upload")
     */
    public function uploadAction()
    {
        $request = $this->get('request');
        $id = $request->get('id');
        $files = $request->files->all();

        if ($files) {
            $newTime = time();

            $em = $this->getDoctrine()->getManager();
            $imageTerm = $em->getRepository('CmsBundle:term')->findOneBy(['identify'=>'image', 'pid'=>0]);
            if (!$imageTerm) {
                return $this->jsonOut([], 1, "图片分类不存在！");
            }

            foreach ($files as $file) {
                $sign = Image::mkSign($file->getPathname());
                //插入数据库
                $img = $em
                    ->getRepository('CmsBundle:image')
                    ->findOneBy(['sign'=>$sign, 'deltime'=>0]);

                if (!$img) {
                    $dst  = $this->get('kernel')->getRootDir() . self::UPLOAD_IMAGE_DIR . '/' . $sign;
                    $name = '0.'.$file->guessClientExtension();
                    //复制到目标路径
                    $file->move($dst, $name);
                    //生成缩略图
                    Image::resize($dst.'/'.$name, 150, 150, true, $dst.'/1.'.$file->guessClientExtension());

                    $url = [
                        'http://www.cms.pcom/upload/image/'.$sign.'/0.'.$file->guessClientExtension(),
                        'http://www.cms.pcom/upload/image/'.$sign.'/1.'.$file->guessClientExtension(),
                    ];
                } else {
                    $url = $img->getUrl();
                }

                $newImg = new \Yearnfar\Bundle\CmsBundle\Entity\image();
                $newImg
                    ->setTerm($imageTerm)
                    ->setName('')
                    ->setDescription('')
                    ->setSign($sign)
                    ->setUrl($url)
                    ->setLogtime($newTime)
                    ->setDeltime(0);

                $em->persist($newImg);
                $em->flush();
            }
            return $this->jsonOut([]);
        } elseif ($id>0) {
            $em = $this->getDoctrine()->getManager();
            $current = $em->find("CmsBundle:image", $id);
            $ots = $em
                ->createQuery("SELECT t FROM CmsBundle:term t WHERE t.identify=?1 OR SUBSTRING(t.identify, 1, 6)=?2")
                ->setParameter(1, 'image')
                ->setParameter(2, 'image_')
                ->getResult();

            $term = [];
            $this->enumTerm($term, $ots, 0, -1);

            return ['oper'=>'modify', 'current'=>$current, 'term'=>$term];
        }

        return ['oper'=>''];
    }

    /**
     * @Route("/delete")
     * @Template()
     */
    public function deleteAction()
    {
        $request = $this->get('request');
        $id = $request->get('id');

        $em = $this->getDoctrine()->getManager();
        $affectNum = $em
            ->createQuery("UPDATE CmsBundle:image i SET i.deltime=?1 WHERE i.id=?2")
            ->setParameter(1, time())
            ->setParameter(2, $id)
            ->getResult();

        if (!$affectNum) {
            return $this->jsonOut([], 1, '删除失败！');
        }

        return $this->jsonOut([]);
    }

    /**
     * @Route("/recycle")
     */
    public function recycleAction()
    {
        $em = $this->getDoctrine()->getManager();
        $cq = $em
            ->createQuery("SELECT i FROM CmsBundle:image i WHERE i.deltime>?1 ORDER BY i.logtime DESC")
            ->setParameter(1, 0)
            ->setMaxResults(50);

        $images = $cq->getResult();
        $img = [];

        foreach ($images as $image) {
            $day = date('Y年m月d日', $image->getLogtime());

            $img[$day][] = $image;
        }

        return ['img' => $img];
    }

    /**
     * @Route("/delete2")
     */
    public function delete2Action()
    {
        $request = $this->get('request');
        $id = $request->get('id');

        $em = $this->getDoctrine()->getManager();
        $img = $em->find('CmsBundle:image', $id);

        if (!$img) {
            return $this->jsonOut([], 1, '删除失败！');
        }

        $sign = $img->getSign();
        $dst  = $this->get('kernel')->getRootDir() . self::UPLOAD_IMAGE_DIR . '/' . $sign;
        $this->enumRmDir($dst);

        $em->remove($img);
        $em->flush();

        return $this->jsonOut([]);
    }

    /**
     * @Route("/undo")
     */
    public function undoAction()
    {
        $request = $this->get('request');
        $id = $request->get('id', 0);

        $em = $this->getDoctrine()->getManager();
        $img = $em->find('CmsBundle:image', $id);

        if (!$img) {
            return $this->jsonOut([], 1, '恢复失败！');
        }

        $img->setDeltime(0);
        $em->flush();

        return $this->jsonOut([]);
    }

}
